package com.atguigu.dw.gmalllogger.contorll;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.constan.ConstanVal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author ：剧情再美终是戏
 * @description：数据采集服务器controll
 * @mail : 13286520398@163.com
 * @date ：Created in 2020/2/10 20:01
 * @modified By：
 * @version: 1.0$
 */
@RestController
public class LoggerController {

    private Logger logger = LoggerFactory.getLogger(LoggerController.class);

    @PostMapping("/log")
    public String doLog(@RequestParam("log") String log) {

        // 对数据添加时间戳
        log = addTs(log);

        // 参数拦截
        if (StringUtils.isEmpty(log)) {
            return log;
        }

        // 将数据落盘
        saveToTextFile(log);

        // 将数据写入kafka
        saveToKafka(log);

        // 直接将传入的数据返回
        return log;
    }

    @Autowired
    KafkaTemplate<String, String> kafkaTemplate;

    private void saveToKafka(String log) {
        // 主义主题
        String topic = ConstanVal.KAFKA_TOPIC_EVENT();
        if (log.contains("\"logType\":\"startup\"")) {
            topic = ConstanVal.KAFKA_TOPIC_START();
        }

        // 将数据写放kafka
        kafkaTemplate.send(topic, log);
    }

    /**
     * 将数据落盘(使用log4j功能直接落盘，方便数仓需要对该数据进行采集)
     *
     * @param log
     * @return void
     * @Author 剧情再美终是戏
     * @Date 2020/2/10 20:21
     * @Version 1.0
     **/
    private void saveToTextFile(String log) {
        logger.info(log);
    }

    /**
     * 对数据添加时间戳
     *
     * @param log
     * @return void
     * @Author 剧情再美终是戏
     * @Date 2020/2/10 20:18
     * @Version 1.0
     **/
    private String addTs(String log) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(log);
            jsonObject.put("ts", System.currentTimeMillis());
            return jsonObject.toJSONString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
